package com.merchant.manage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.merchant.constant.Constants;
import com.merchant.fragment.SwipeListView;
import com.merchant.json.ReadJson;
import com.merchant.util.AsycImageLoader;
import com.merchant.util.LoadingDialog;
import com.umeng.analytics.MobclickAgent;
import com.zjxfood.merchant.activity.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.ToggleButton;

public class FoodsManagementActivity extends Activity implements
		OnClickListener {
	private SwipeListView mListView;
	private List<Map<String, Object>> mlistitem;
	private TextView manage_caipin_add_text;
	private HashMap<String, Object> mUserMapLists;
	private HashMap<String, Object> UserMapLists;
	private ArrayList<HashMap<String, Object>> mMap;
	private ArrayList<HashMap<String, Object>> mDataList;
	private ArrayList<HashMap<String, Object>> addDataList;
	private MyAdapter adapter;
	private String page = "1";
	private int lastVisibleIndex;
	private int x = 1;
	private RunTask mRunTask;
	private ImageView manage_caipin_back_image;
	private LoadingDialog dialog;
	private AsycImageLoader imageloader;
	private Bitmap bitmap = null;// 图片对象
	private int pos;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_manage_caipin);
		// new Thread(GetDishesInfo).start();
		// new Thread(GetDishesList).start();
		dialog = new LoadingDialog(this);
		dialog.show();
		mRunTask = new RunTask();
		mRunTask.execute("");
		// new Thread(GetUpdateStatus).start();
		init();

	}

	private void init() {
		mListView = (SwipeListView) findViewById(R.id.caipin_listview);
		manage_caipin_add_text = (TextView) findViewById(R.id.manage_caipin_add_text);
		manage_caipin_back_image = (ImageView) findViewById(R.id.manage_caipin_back_image);
		manage_caipin_back_image.setOnClickListener(this);
		manage_caipin_add_text.setOnClickListener(this);
		mListView.setOnScrollListener(mScrollListener);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.manage_caipin_add_text:
			intent.setClass(getApplicationContext(), AddFoodsAddActivity.class);
			// Bundle bundle = new Bundle();
			// bundle.putString("id", "");
			// intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.manage_caipin_back_image:
			finish();
			break;
		}
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	Runnable GetDishesList = new Runnable() {

		@Override
		public void run() {
			try {
				String ss = "mobileAppUserType=" + 2 + "&Mid=" + 32
						+ "&pagesize=" + 10 + "&currentPage=" + 1 + "&orderBy="
						+ 0;
				String sign = Constants.sortsStr(ss);
				String str = Constants.GetDishesList + sign
						+ "&mobileAppUserType=" + 2 + "&Mid=" + 32
						+ "&pagesize=" + 10 + "&currentPage=" + 1 + "&orderBy="
						+ 0;
				String json = ReadJson.readParse(str);
				// Log.i("sign", "================" + json);
				mMap = Constants.getJsonArray(json);
				// mDataList = Constants.getJsonArray(mUserMapLists.get("Data")
				// .toString());
				Log.i("mMap", "================" + mMap);
				// handler.sendEmptyMessageDelayed(1, 0);
				dialog.dismiss();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	Runnable GetUpdateStatus = new Runnable() {

		@Override
		public void run() {
			try {
				String ss = "id=" + 27 + "&currentMId=" + Constants.Id
						+ "&isSale=" + 1;
				String sign = Constants.sortsStr(ss);
				String str = Constants.GetUpdateStatus + sign + "id=" + 27
						+ "&currentMId=" + Constants.Id + "&isSale=" + 1;
				String json = ReadJson.readParse(str);
				mUserMapLists = Constants.getJson2Object(json);
				mDataList = Constants.getJsonArray(mUserMapLists.get("Data")
						.toString());
				Log.i("mUserMap", "================" + mUserMapLists);
				// handler.sendEmptyMessageDelayed(1, 0);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	class RunTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... strs) {
			switch (x) {
			case 1:
				try {
					String ss = "mobileAppUserType=" + 2 + "&Mid=" + 32
							+ "&pagesize=" + 10 + "&currentPage=" + page
							+ "&orderBy=" + 0;
					String sign = Constants.sortsStr(ss);
					String str = Constants.GetDishesList + sign
							+ "&mobileAppUserType=" + 2 + "&Mid=" + 32
							+ "&pagesize=" + 10 + "&currentPage=" + page
							+ "&orderBy=" + 0;
					String json = ReadJson.readParse(str);
					// Log.i("sign", "================" + json);
					mUserMapLists = Constants.getJson2Object(json);
					mDataList = Constants.getJsonArray(mUserMapLists
							.get("Data").toString());
					// mMap = Constants.getJsonArray(json);
					handler.sendEmptyMessageDelayed(1, 0);
					Log.i("mDataList", "================" + mDataList);
					dialog.dismiss();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					dialog.dismiss();
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				break;

			case 2:
				String ss = "&mobileAppUserType=" + 2 + "Mid=" + 32
						+ "&pagesize=" + 10 + "&currentPage=" + page
						+ "&orderBy=" + 0;
				String sign = Constants.sortsStr(ss);
				String str = Constants.GetDishesList + sign
						+ "&mobileAppUserType=" + 2 + "&Mid=" + 32
						+ "&pagesize=" + 10 + "&currentPage=" + page
						+ "&orderBy=" + 0;
				String json;

				try {
					json = ReadJson.readParse(str);
					mUserMapLists = Constants.getJson2Object(json);
					addDataList = Constants.getJsonArray(mUserMapLists.get(
							"Data").toString());
					dialog.dismiss();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					dialog.dismiss();
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				handler.sendEmptyMessageDelayed(2, 0);
				break;
			}

			return null;
		}
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				adapter = new MyAdapter(getApplicationContext(),
						mListView.getRightViewWidth(), mDataList);
				mListView.setAdapter(adapter);
				mListView.setVisibility(View.VISIBLE);
				mListView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getApplicationContext(),
								AddFoodsActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("id", mDataList.get(arg2).get("Id")
								.toString());
						intent.putExtras(bundle);
						startActivity(intent);
					}
				});
				break;
			case 2:
				adapter.nofity(addDataList);
				break;
			case 3:
				Toast.makeText(getApplicationContext(), "请检查您的网络链接!",
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				mListView.deleteItem(mListView.getChildAt(pos));
				adapter.delete(pos);
				adapter.notifyDataSetChanged();
				break;
			}
		};
	};
	OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
					&& lastVisibleIndex == adapter.getCount() - 1) {
				x = 2;
				// lv.addFooterView(mFooterView);// 添加 加载更多
				page = Integer.parseInt(page) + 1 + "";
				mRunTask = new RunTask();
				mRunTask.execute("");
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 计算最后可见条目的索引
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
		}
	};

	public final class ViewHolder {
		public TextView user_reviews_text1;
		public TextView user_reviews_text2;
		public TextView user_reviews_text3;
		public RelativeLayout item_right;
		public ImageView caipin_image;
		public CheckedTextView shangjia_text;
		public ToggleButton foods_check;
	}

	/**
	 * 单击事件监听器
	 */
	public interface onRightItemClickListener {
		void onRightItemClick(View v, int position);
	}

	public class MyAdapter extends BaseAdapter {
		private onRightItemClickListener mListener = null;
		private LayoutInflater flater;
		private ArrayList<HashMap<String, Object>> mList;
		private int mRightWidth = 1;

		public MyAdapter(Context content, int rightWidth,
				ArrayList<HashMap<String, Object>> list) {
			this.flater = LayoutInflater.from(content);
			mRightWidth = rightWidth;
			this.mList = list;
		}

		public void setOnRightItemClickListener(
				onRightItemClickListener listener) {
			mListener = listener;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void nofity(ArrayList<HashMap<String, Object>> list) {
			try {
				this.mList.addAll(list);
				notifyDataSetChanged();
			} catch (Exception e) {
				// TODO: handle exception
				handler.sendEmptyMessageDelayed(3, 0);
			}

		}

		public void delete(int del) {
			mList.remove(del);
			notifyDataSetChanged();
		}

		@Override
		public View getView(final int position, View converView,
				ViewGroup parent) {
			// TODO Auto-generated method stub
			final ViewHolder hodler;
			if (converView == null) {
				hodler = new ViewHolder();
				imageloader = new AsycImageLoader();
				converView = flater.inflate(
						R.layout.manage_foods_order_list_item, null);

				hodler.user_reviews_text1 = (TextView) converView
						.findViewById(R.id.d);
				hodler.user_reviews_text2 = (TextView) converView
						.findViewById(R.id.d1);
				hodler.user_reviews_text3 = (TextView) converView
						.findViewById(R.id.d2);
				hodler.caipin_image = (ImageView) converView
						.findViewById(R.id.caipin_image);
				hodler.item_right = (RelativeLayout) converView
						.findViewById(R.id.item_right);
				hodler.foods_check = (ToggleButton) converView
						.findViewById(R.id.foods_check);
				hodler.shangjia_text = (CheckedTextView) converView
						.findViewById(R.id.shangjia_text);
				converView.setTag(hodler);
			} else {
				hodler = (ViewHolder) converView.getTag();
			}
			LinearLayout.LayoutParams lp2 = new LayoutParams(mRightWidth,
					LayoutParams.MATCH_PARENT);
			hodler.item_right.setLayoutParams(lp2);
			hodler.user_reviews_text1.setText(mList.get(position).get("name")
					.toString());
			hodler.user_reviews_text2.setText(mList.get(position).get("price")
					.toString());
			hodler.user_reviews_text3.setText(mList.get(position).get("cost")
					.toString());
			hodler.foods_check
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton arg0,
								boolean arg1) {
							if (arg1) {
								hodler.shangjia_text.setText("已上架");
								hodler.shangjia_text.setChecked(true);
								hodler.foods_check.setClickable(true);
							} else {
								if (mList.get(position).get("status")
										.toString().equals("-1")) {
									hodler.shangjia_text.setText("拒绝");
									hodler.foods_check.setChecked(false);
									hodler.shangjia_text.setChecked(false);
									hodler.foods_check.setClickable(false);
								} else if (mList.get(position).get("status")
										.toString().equals("0")) {
									hodler.shangjia_text.setText("待审核");
									hodler.foods_check.setChecked(false);
									hodler.shangjia_text.setChecked(false);
									hodler.foods_check.setClickable(false);
								} else if (mList.get(position).get("status")
										.toString().equals("1")) {
									hodler.shangjia_text.setText("已下架");
									hodler.foods_check.setChecked(false);
									hodler.shangjia_text.setChecked(false);
									hodler.foods_check.setClickable(true);
								} else if (mList.get(position).get("status")
										.toString().equals("2")) {
									hodler.shangjia_text.setText("已删除");
									hodler.foods_check.setChecked(false);
									hodler.shangjia_text.setChecked(false);
									hodler.foods_check.setClickable(false);
								}
							}
						}
					});
			Log.i("ddd", mList.get(position).get("status").toString() + "");
			if (mList.get(position).get("status").toString().equals("-1")) {
				hodler.shangjia_text.setText("拒绝");
				hodler.foods_check.setChecked(false);
				hodler.shangjia_text.setChecked(false);
				hodler.foods_check.setClickable(false);
			} else if (mList.get(position).get("status").toString().equals("0")) {
				hodler.shangjia_text.setText("待审核");
				hodler.foods_check.setChecked(false);
				hodler.shangjia_text.setChecked(false);
				hodler.foods_check.setClickable(false);
			} else if (mList.get(position).get("status").toString().equals("1")) {
				hodler.shangjia_text.setText("已上架");
				hodler.foods_check.setChecked(true);
				hodler.shangjia_text.setChecked(true);
				hodler.foods_check.setClickable(true);
			} else if (mList.get(position).get("status").toString().equals("2")) {
				hodler.shangjia_text.setText("已删除");
				hodler.foods_check.setChecked(false);
				hodler.shangjia_text.setChecked(false);
				hodler.foods_check.setClickable(false);
			}
			if (mList.get(position).get("image") != null) {
				bitmap = imageloader.showImageAsyn(hodler.caipin_image, mList
						.get(position).get("image").toString(),
						R.drawable.foods_order_photo);
				hodler.caipin_image.setImageBitmap(bitmap);
			}

			final Runnable GetDelete = new Runnable() {

				@Override
				public void run() {
					try {
						String ss = "id="
								+ mList.get(position).get("Id").toString()
								+ "&currentMid=" + 32;
						String sign = Constants.sortsStr(ss);
						String str = Constants.GetDelete + sign + "&id="
								+ mList.get(position).get("Id").toString()
								+ "&currentMid=" + 32;
						String json = ReadJson.readParse(str);
						mUserMapLists = Constants.getJson2Object(json);
						Log.i("Id", "================"
								+ mList.get(position).get("Id").toString());
						Log.i("json", "================" + mUserMapLists);
						handler.sendEmptyMessageDelayed(4, 0);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						handler.sendEmptyMessageDelayed(3, 0);
						e.printStackTrace();
					}
				}
			};
			hodler.item_right.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.i("position", "================" + position);
					Log.i("position1", "================" + mList.get(position));
					pos = position;
					new Thread(GetDelete).start();
				}
			});
			return converView;
		}
	}
}
